package com.aiju.cash.ui.enter;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.ui.enter.util.CityData;
import com.aiju.forexpand.addresspicker.AddressPicker;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.widgit.layout.SettingItemEditView;
import com.aiju.widgit.layout.SettingItemTextView;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapOptions;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;

/**
 * @author: 佐为
 * @date: 2017-05-26 09:47
 * @version: V1.0
 * @Description: 店铺首页上传
 */
public class AdressActivity extends BaseTitleActivity {
    private TextView sumTextView;
    private SettingItemTextView category;
    private SettingItemEditView addressView;
    private String codeName, address;
    private String province_code, city_code, district_code;//地址code

    private AMap aMap;
    private MapView mapView;
    private GeocodeSearch codeSearch;//查坐标

    private String longitude;
    private String latitude;
    private LinearLayout linearLayout;

    private Marker marker;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adress);
        setCenterTitle("门店地址");
        setRightTitle("保存");

        codeName = getIntent().getStringExtra("codeName");
        address = getIntent().getStringExtra("address");
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        province_code = getIntent().getStringExtra("province_code");
        city_code = getIntent().getStringExtra("city_code");
        district_code = getIntent().getStringExtra("district_code");

        linearLayout = (LinearLayout) findViewById(R.id.layout);
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(codeName)) {
                    T.ToastShort("请选择省市区");
                    return;
                }
                address = addressView.getRightString();
                if (TextUtils.isEmpty(address)) {
                    T.ToastShort("请输入详细地址");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("codeName", codeName);
                intent.putExtra("address", address);
                intent.putExtra("longitude", longitude);
                intent.putExtra("latitude", latitude);
                intent.putExtra("province_code", province_code);
                intent.putExtra("city_code", city_code);
                intent.putExtra("district_code", district_code);
                setResult(200, intent);
                finish();
            }
        });
        sumTextView = (TextView) findViewById(R.id.tv_sum);
        addressView = (SettingItemEditView) findViewById(R.id.set_store_other_name);
        addressView.setEditable(true);
        addressView.getRightView().setHint("请输入详细地址，精确到街道名称、门牌号码、楼层和房间号");
        addressView.getRightView().setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
        addressView.getRightView().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sumTextView.setText(s.length() + "/50");
            }
        });
        category = (SettingItemTextView) findViewById(R.id.set_store_name);
        category.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityData.showAreaDialog(AdressActivity.this, new AddressPicker.OnChangeCity() {
                    @Override
                    public void onChangeCity(String province, String city, String area) {
                        province_code = CityData.getCode(province);
                        city_code = CityData.getCode(city);
                        district_code = CityData.getCode(area);
                        codeName = CityData.getAllAddress(province, city, area);
                        category.getRightView().setText(codeName);
                    }
                });
            }
        });
        if (!TextUtils.isEmpty(codeName)) {
            category.setRightText(codeName);
        }
        if (!TextUtils.isEmpty(address)) {
            addressView.setRightText(address);
            ((EditText) addressView.getRightView()).setSelection(address.length());
        }

        findViewById(R.id.btn_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(codeName)) {
                    T.ToastShort("请选择省市区");
                    return;
                }
                address = addressView.getRightString();
                if (TextUtils.isEmpty(address)) {
                    T.ToastShort("请输入详细地址");
                    return;
                }
                searchCode(codeName.replaceAll("-", "") + address);
            }
        });

        if (TextUtils.isEmpty(latitude) || TextUtils.isEmpty(longitude)) {
            latitude = "30.287803";
            longitude = "120.059654";
        }
        addMap(savedInstanceState);


        codeSearch = new GeocodeSearch(this);
        codeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                if (rCode == 1000) {
                    if (result != null && result.getRegeocodeAddress() != null) {
                        RegeocodeAddress regeocodeAddress = result.getRegeocodeAddress();
                        String formatAddress = regeocodeAddress.getFormatAddress();
                        String shortAdd = formatAddress.replace(regeocodeAddress.getProvince(), "").replace(regeocodeAddress.getCity(), "").replace(regeocodeAddress.getDistrict(), "");
                        addressView.setRightText(shortAdd);
                        T.ToastShort(formatAddress);
                    } else {
                        T.ToastShort("请输入正确的坐标");
                    }
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int rCode) {
                if (rCode == 1000) {
                    if (result != null && result.getGeocodeAddressList() != null && result.getGeocodeAddressList().size() > 0) {
                        GeocodeAddress addressCode = result.getGeocodeAddressList().get(0);
                        latitude = String.valueOf(addressCode.getLatLonPoint().getLatitude());
                        longitude = String.valueOf(addressCode.getLatLonPoint().getLongitude());
                        addMap(savedInstanceState);
                    } else {
                        T.ToastShort("请输入正确的地址");
                    }
                }
            }
        });
    }

    /**
     * 添加map
     */
    public void addMap(Bundle savedInstanceState) {
        if (mapView != null) {
            linearLayout.removeView(mapView);
            mapView.onDestroy();
        }
        LatLng centerBJPoint = new LatLng(Double.valueOf(latitude), Double.valueOf(longitude));
        AMapOptions mapOptions = new AMapOptions();
        mapOptions.camera(new CameraPosition(centerBJPoint, 10f, 0, 0));
        mapView = new MapView(this, mapOptions);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        linearLayout.addView(mapView);

        aMap = mapView.getMap();
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));//地图的缩放级别一共分为 18 级，从 3 到 21。数字越大，展示的图面信息越精细。
        aMap.addMarker(new MarkerOptions()
                .position(new LatLng(Double.valueOf(latitude), Double.valueOf(longitude)))
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.browspic)))
                .draggable(true));
        aMap.setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {

            }

            @Override
            public void onMarkerDrag(Marker marker) {

            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                LatLng position = marker.getPosition();
                latitude = String.valueOf(position.latitude);//维度
                longitude = String.valueOf(position.longitude);//经度
                L.d("维度:" + latitude);
                L.d("经度:" + latitude);
                searchAddress();
            }
        });
    }

    /**
     * 根据坐标查地址
     */
    private void searchAddress() {
        LatLonPoint centerBJPoint = new LatLonPoint(Double.valueOf(latitude), Double.valueOf(longitude));
        RegeocodeQuery query = new RegeocodeQuery(centerBJPoint, 200f, GeocodeSearch.AMAP);
        codeSearch.getFromLocationAsyn(query);
    }

    /**
     * 根据地址查坐标
     */
    private void searchCode(String address) {
        GeocodeQuery query = new GeocodeQuery(address, "");
        codeSearch.getFromLocationNameAsyn(query);
    }

}
